import json
import traceback

import requests

from shop.conf import MIAO_APKEY, PID, TB_NAME
from shop.util.mylogger import Alogger


def do_request(method, data, url, **kwargs):
    """
    单次执行请求
    :return:
    """
    try:
        if method == "get":
            if data:
                res = requests.get(url, params=data, **kwargs)
            else:
                res = requests.get(url, **kwargs)
        else:
            if data:
                res = requests.post(url, data=json.dumps(data), **kwargs)
            else:
                res = requests.post(url, **kwargs)
    except:
        exception_detail = traceback.format_exc()
        Alogger.error(exception_detail)
        return None
    return res.json()


class MiaoHandler:
    def __init__(self):
        self.appkey = MIAO_APKEY
        self.pid = PID
        self.tb_name = TB_NAME

        self.taoqiaogou_url = "http://api.web.ecapi.cn/platform/getItemList"  # 抢购url

    def req_taoqianggou_juhuasuan_get(self, **kwargs):
        """
        请求淘抢购、聚划算、9.9包邮的秒杀商品
        :return:
        """
        Alogger.debug("请求喵有券，淘抢购、聚划算商品接口所传的参数：", kwargs)
        kwargs["apkey"] = self.appkey
        res = do_request("get", kwargs, self.taoqiaogou_url)
        return res
